package com.vip.jwt.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vip.jwt.common.entity.R;
import com.vip.jwt.entity.Menu;
import com.vip.jwt.entity.Role;
import com.vip.jwt.service.MenuService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author vip
 * @since 2021-05-04
 */
@RestController
@RequestMapping("/api/menu")
public class MenuController extends BaseController{

    @Resource
    private MenuService menuService;

    @PostMapping
    public Object addMenu(@RequestBody Menu menu){
        menuService.save(menu);
        return R.ok();
    }

    @DeleteMapping("/{id}")
    public Object deleteById(@PathVariable String id){
        menuService.deleteById(id);
        return R.ok();
    }

    @PutMapping
    public Object updateMenu(@RequestBody Menu menu){
        menuService.updateById(menu);
        return R.ok();
    }

    @GetMapping("/tree")
    public Object tree(){
        return R.ok().data("items",menuService.tree());
    }

    @GetMapping("/tree/auth")
    public Object treeAuth(){
        List<Role> roles = getUser().getRoles();
        boolean flag = false;
        for(int i=0;i<roles.size();i++){
            Role role = roles.get(i);
            if("super_admin".equals(role.getCode())){
                flag = true;
            }
        }
        if(flag){
            return R.ok().data("items",menuService.tree());
        }else{
            List<String> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());
            if(roleIds.size()>0){
                return R.ok().data("items",menuService.tree(roleIds));
            }else{
                return R.ok().data("items",new ArrayList<>());
            }
        }
    }

    @ApiOperation("获取菜单列表（分页）")
    @GetMapping("/{page}/{limit}")
    public Object pageList(@PathVariable Long page,@PathVariable Long limit){
        Page<Menu> menuPage = new Page<>(page,limit);
        Page<Menu> menus = menuService.page(menuPage);
        return R.ok().data("data",menus);
    }

}

